package com.muki.succ.registery;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.SAXException;

import com.muki.spider.SpiderManager;
import com.muki.succ.core.Manager;
import com.muki.succ.core.ManagerConfiResolver;

/**
 * 爬虫管理者集群
 * @author ljh_2017
 *
 */
public class SpiderManagerHall {

	private final ManagerConfiResolver handler = new ManagerConfiResolver();
	private static final SpiderManagerHall HALL = new SpiderManagerHall();
	SpiderManager[] managers;
	
	public static SpiderManagerHall newInstance() {
		return HALL;
	}
	
	public SpiderManagerHall() {
		InputStream is = SpiderManagerHall.class.getResourceAsStream("/manager.xml");
		SAXParserFactory factory = SAXParserFactory.newInstance();
		SAXParser parser = null;
		
		try {
			parser = factory.newSAXParser();
			parser.parse(is, handler);
			List<Manager> list = handler.getList();
			int size = list.size();
			managers = new SpiderManager[size];
			for(int i=0;i<size;i++) {
				managers[i] = registerManager(list.get(i));
			}
		} catch (ParserConfigurationException | SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@SuppressWarnings("unchecked")
	private SpiderManager registerManager(Manager manager) {
		if(manager==null)
			return null;
		String[] temp = manager.toString().split(" ");
		String driver = temp[0];
		String topic = temp[1];
		String regx = temp[2];
		try {
			Class<SpiderManager> cls = (Class<SpiderManager>) Class.forName(driver);
			SpiderManager obj = cls.newInstance();
			Method topicMethod = cls.getMethod("setTopic", String.class);
			Method regxMethod = cls.getMethod("setRegx", String.class);
			topicMethod.invoke(obj, topic);
			regxMethod.invoke(obj, regx);
			if(obj!=null) {
				return obj;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return null;
	}
	
	public SpiderManager findByName(String name) {
		int index = handler.getIndex(name);
		if(index != -1) {
			return managers[index];
		}
		return null;
	}
	
	public List<Manager> getAllManager() {
		return handler.getList();
	}
}
